Skip to main content

Singleton

Ensures that a class has only one instance and provides a global point of access to it.

Structure

  • Private constructor: This prevents other classes from creating new instances.
  • Static private instance: This holds the single instance of the class.
  • Static method (getInstance): Provides a global point of access to the instance.

Example

class Singleton {
// Step 1: Create a private static instance of the class.
private static Singleton instance;

// Step 2: Make the constructor private to prevent instantiation.
private Singleton(){
System.out.println("Object Created");
...
}

// Step 3: Provide a public static method to get the instance.
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}

public class Main{
public static void main(String[] args){
Singleton a1 = Singleton.getInstance();
Singleton a2 = Singleton.getInstance();
Singleton a3 = Singleton.getInstance();
Singleton a4 = Singleton.getInstance();
Singleton a5 = Singleton.getInstance();
// Singleton a2 = new Singleton();
}
}